#include <stdio.h>
#include <stdlib.h>
#include <libusb-1.0/libusb.h>

#include "module.h"

// #define VENDOR_ID 0x0e0f // 你的鼠标的供应商ID
// #define PRODUCT_ID 0x0003 // 你的鼠标的产品ID
// 有线鼠标
// #define VENDOR_ID 0x093a // 你的鼠标的供应商ID
// #define PRODUCT_ID 0x2510 // 你的鼠标的产品ID
// #define ENDPOINT_IN 0x81 // 输入端点

// 无线鼠标
#define VENDOR_ID 0x25a7 // 你的鼠标的供应商ID
#define PRODUCT_ID 0xfa23 // 你的鼠标的产品ID
#define ENDPOINT_IN 0x82 // 输入端点
#define MAX_BUF_SIZE 8 // 最大缓冲区大小

#if 0
int main() {
    libusb_device_handle *devh = NULL;
    int ret;
    unsigned char buf[MAX_BUF_SIZE];

    hello();

    while(1);

    ret = libusb_init(NULL);
    if (ret < 0) {
        fprintf(stderr, "Error initializing libusb: %s\n", libusb_error_name(ret));
        return 1;
    }

    devh = libusb_open_device_with_vid_pid(NULL, VENDOR_ID, PRODUCT_ID);
    if (!devh) {
        fprintf(stderr, "Could not find/open USB device.\n");
        return 1;
    }

    libusb_set_auto_detach_kernel_driver(devh, 1);

    ret = libusb_claim_interface(devh, 0);
    if (ret < 0) {
        fprintf(stderr, "Cannot claim interface: %s\n", libusb_error_name(ret));
        return 1;
    }

    printf("Reading data from the mouse...\n");

    while (1) {
        int actual_length;
        ret = libusb_interrupt_transfer(devh, ENDPOINT_IN, buf, sizeof(buf), &actual_length, 5000);
        if (ret == 0 && actual_length == MAX_BUF_SIZE) {
            // 在这里处理数据报告
            printf("Received data: ");
            for (int i = 0; i < actual_length; i++) {
                printf("%02x ", buf[i]);
            }
            printf("\n");
        } else if (ret == LIBUSB_ERROR_TIMEOUT) {
            fprintf(stderr, "libusb_interrupt_transfer timout\n");
        } else {
            fprintf(stderr, "Interrupt transfer error: %s\n", libusb_error_name(ret));
            break;
        }
    }

    libusb_release_interface(devh, 0);
    libusb_close(devh);
    libusb_exit(NULL);

    return 0;
}
#endif
static void print_devs(libusb_device **devs)
{
	libusb_device *dev;
	int i = 0, j = 0;
	uint8_t path[8]; 

	while ((dev = devs[i++]) != NULL) {
		struct libusb_device_descriptor desc;
		int r = libusb_get_device_descriptor(dev, &desc);
		if (r < 0) {
			fprintf(stderr, "failed to get device descriptor");
			return;
		}

		printf("%04x:%04x (bus %d, device %d)",
			desc.idVendor, desc.idProduct,
			libusb_get_bus_number(dev), libusb_get_device_address(dev));

		r = libusb_get_port_numbers(dev, path, sizeof(path));
		if (r > 0) {
			printf(" path: %d", path[0]);
			for (j = 1; j < r; j++)
				printf(".%d", path[j]);
		}
		printf("\n");
	}
}

int main(void)
{
	libusb_device **devs;
	int r;
	ssize_t cnt;

	r = libusb_init_context(/*ctx=*/NULL, /*options=*/NULL, /*num_options=*/0);
	if (r < 0)
		return r;

	cnt = libusb_get_device_list(NULL, &devs);
	if (cnt < 0){
		libusb_exit(NULL);
		return (int) cnt;
	}

	print_devs(devs);
	libusb_free_device_list(devs, 1);

	libusb_exit(NULL);

	return 0;
}